// myself/file/QiyeFilePost.js
import api from "../../utils/api.js";
import utils from "../../utils/utils.js";
import network from "../../utils/network.js";
import formatDate from "../../utils/format_date.js";
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    finish: true,
    filename: null,
    filePath: null,
    fileId: [],
    signPath: '',
    fileTypes: ['公科经文', '公科经发','公科经党组','公工领发'],
    fileType: null,
    sysmodenum:'miniofficid',
    shownext:false,
    nextUsers:[],
    dataNextUser:[],
    nextnameid:'',
    nextnames:'',
    nexuids:'',
    setid:117,

    isHidden: true,//原始添加
    url: [],//上传文件路径
    type: '',//上传文件类型
    uploaderList: [],//上传文件数组
    showModal: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    network.postJson(this, api.getFiletypes, {
      adminid: app.globalData.userInfo.uid,
      token: app.globalData.userInfo.token,
      pid: 'qiyeofficiaclass',
    }).then(res => {
     if(res.data.data){
       var resdata = res.data.data;
       var types = [];
      for (const key in resdata) {
        types.push(resdata[key]['name'])
      }
      this.setData({
        fileTypes:types
      })
     }
    })
    this.signature = this.selectComponent("#signature");
    this.toast = this.selectComponent("#toast");
    network.postJson(this, api.getNext, {
      adminid: app.globalData.userInfo.uid,
      token: app.globalData.userInfo.token,
      setid: this.data.setid,
    }).then(res => {
      console.log(res.data.data)
      if(res.data.data.shownext){
        let arr = [];
        let nexname = [];
        var result = res.data.data.nextUser;
        for (const key in result) {
          arr.push(result[key].id);
          nexname.push(result[key].name)
        }
        var nexuids = arr.join(',')
        var nextnames = nexname.join(',')
        this.setData({
          nexuids:nexuids,
          nextnames:nextnames,
          nextUsers:arr,
          dataNextUser:res.data.data.nextUser,
          nextName:res.data.data.nextName
        })
      }
      this.setData({
        shownext: res.data.data.shownext,
        sysnextcustidid:res.data.data.sysnextcustidid
      })
    })
  },

  bindNextChange:function(e){
    let nexuids = e.currentTarget.dataset.nexuids
      wx.navigateTo({
        url: '/myself/file/ChooseUser?nexuids=' + nexuids + '&selectid=' + this.data.nextnameid + '&nextname=' + this.data.nextname
    })
    },

    upload() {
      let that = this;
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFiles
          let url = app.globalData.debug ? api.debugUrl : api.url
          wx.uploadFile({
            url: url + api.upFile, //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0].path,
            name: 'file',
            formData: {
              adminid: app.globalData.userInfo.uid,
              token: app.globalData.userInfo.token,
              cfrom: "weixin",
              device: app.globalData.device
            },
            success(res) {
              const data = res.data
              console.log(JSON.parse(res.data).id)
              that.data.fileId =JSON.parse(res.data).id
              that.setData({
                filename: JSON.parse(res.data).filename
              })
            }
          })
        }
      })
    },

    // // 上传图片
    upImg() {
      var that = this
  
      wx.chooseMessageFile({
        count: 1,
        type: 'all',
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          //  console.log('vvvvvvvv',res.tempFiles)
  
          const tempFilePaths = res.tempFiles[0].path
          const type = res.tempFiles[0].type
          let url = app.globalData.debug ? api.debugUrl : api.url
          wx.uploadFile({
            url: url + api.upFile,
            filePath: tempFilePaths,
            name: 'file',
            formData: {
              adminid: app.globalData.userInfo.uid,
              token: app.globalData.userInfo.token,
              cfrom: "weixin",
              device: app.globalData.device
            },
            success(res) {
              const datas = JSON.parse(res.data)
            
              that.data.list
             
              var upFiles = datas.data
              if (upFiles != '') {
                let tempFile = tempFilePaths;
                let uploaderList = that.data.uploaderList.concat(tempFile);
                that.data.url = that.data.url.concat(upFiles);
                let fileId =that.data.fileId.concat(datas.id)
                that.setData({
                  type: type,
                  uploaderList: uploaderList,
                  fileId:fileId
                })
              }
              
            }
          })
  
        }
      })
  
    },
  
    // 删除上传
    close(e) {
      var that = this
      var nowList = [];//新数据
      var uploaderList = that.data.uploaderList;//原数据
  
      for (let i = 0; i < uploaderList.length; i++) {
        if (i == e.currentTarget.dataset.index) {
          continue;
        } else {
          nowList.push(uploaderList[i])
        }
      }
      that.setData({
        uploaderList: nowList,
        isHidden: true
      })
    },

  chooseType() {
    let that = this;
    wx.showActionSheet({
      itemList: this.data.fileTypes,
      success(res) {
        that.setData({
          fileType: that.data.fileTypes[res.tapIndex]
        })
      }
    })
  },

  goSignature() {
    this.signature.openSignature();
  },

  getSignature(src) {
    this.setData({
      path: src.detail
    })
    let that = this;
    let url = app.globalData.debug ? api.debugUrl : api.url
    wx.uploadFile({
      url: url + api.upFile, //仅为示例，非真实的接口地址
      filePath: this.data.path,
      name: 'file',
      formData: {
        adminid: app.globalData.userInfo.uid,
        token: app.globalData.userInfo.token,
        cfrom: "weixin",
        device: app.globalData.device
      },
      success(res) {
        const data = res.data
        that.data.signPath =  JSON.parse(res.data).filepath
      }
    })
  },

  formSubmit: function(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let formValue = e.detail.value;
    if (this.data.fileId.length<=0) {
      this.toast.showToast('请上传文件');
      return;
    } else if (e.detail.value.name == '') {
      this.toast.showToast('请输入文件名');
      return;
    } else if (!this.data.fileType) {
      this.toast.showToast('请选择文件类型');
      return;
    } 
    // else if (!this.data.signPath) {
    //   this.toast.showToast('请上传签名');
    //   return;
    // }
    if(this.data.shownext && (!this.data.nextnameid || !this.data.nextnames)){
      this.toast.showToast('请选择经办人员');
      return;
    }
    if(this.data.shownext && this.data.sysnextcustidid == 0){
      this.toast.showToast('系统错误');
      return;
    }
    var postjson = {}
    if(!this.data.shownext){
      postjson = {
      adminid: app.globalData.userInfo.uid,
      token: app.globalData.userInfo.token,
      id: 0,
      title: e.detail.value.name,
      filecontid: this.data.fileId.join(),
      sysmodenum: this.data.sysmodenum,
      sysmodeid: this.data.setid,
      type: '2',
      class: this.data.fileType,
      //qianming: this.data.signPath
      remarks:e.detail.value.remarks
      }
    }else{
      postjson = {
      adminid: app.globalData.userInfo.uid,
      token: app.globalData.userInfo.token,
      id: 0,
      title: e.detail.value.name,
      filecontid: this.data.fileId.join(),
      sysmodenum: this.data.sysmodenum,
      sysmodeid: this.data.setid,
      type: '2',
      class: this.data.fileType,
      // qianming: this.data.signPath,
      sysnextcustidid:this.data.sysnextcustidid,
      sysnextoptid:this.data.nexuids,
      sysnextopt:this.data.nextnames,
      remarks:e.detail.value.remarks
      }
    }

    network.postJson(this, api.save, postjson).then(res => {
      this.toast.showToast('提交成功');
      wx.navigateBack();
    });
  }
})